package com.example.web.controller;

import com.example.web.mapper.CartMapper;
import com.example.web.mapper.ProductMapper;
import com.example.web.model.Product;
import com.example.web.model.ShoppingCart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpSession;

/**
 * Create by keboom on 2020/7/4
 */
@Controller
public class DetailController {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CartMapper cartMapper;

    /**
     * 获取每个商品的详情页
     * @param id
     * @param model
     * @param session
     * @return
     */
    @GetMapping("/mall/shop/detail/{id}")
    public String detail(@PathVariable("id")Integer id, Model model,
                         HttpSession session){
        Product product = productMapper.selectById(id);
        model.addAttribute("product",product);
        session.setAttribute("productId",id);
        return "details";
    }

    /**
     * 将商品添加到购物车
     * @param session
     * @return
     */
    @GetMapping("/mall/shop/detail/cart")
    public String cart(HttpSession session){
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserName((String) session.getAttribute("username"));
        shoppingCart.setProductId((Integer) session.getAttribute("productId"));
        shoppingCart.setExpired(0);
        cartMapper.insertCart(shoppingCart);
        return "redirect:/mall/shop";
    }
}
